package com.mzba.easy.weibo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.mzba.easy.weibo.db.UserEntry;
import com.mzba.easy.weibo.ui.CommentsTimeLineFragment;
import com.mzba.easy.weibo.ui.FollowersFragment;
import com.mzba.easy.weibo.ui.FriendsFragment;
import com.mzba.easy.weibo.ui.HomeFragment;
import com.mzba.easy.weibo.ui.MentionsTimeLineFragment;
import com.mzba.easy.weibo.ui.NewsActivity;
import com.mzba.easy.weibo.ui.UserTimeLineFragment;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.ServiceUtils;
import com.mzba.easy.weibo.util.WeiboManager;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TabPageIndicator;
import com.viewpagerindicator.TitleProvider;
/**
 * 
 * @author 06peng
 *
 */
public class MainActivity extends BasicActivity implements Callback, ActionBar.OnNavigationListener {
	
	ViewPager mPager;
	PageIndicator mIndicator;
	private TabsAdapter mAdapter;
	private Handler handler;
	private final int get_userinfo = 1;
	public static final int LOADFINISH = 0x00000105;
	
	private final int menu_new = 001;
	private final int menu_refresh = 002;
	
	public ActionBar actionBar;
//	public ProgressBar progressBar;
//	public ImageView avatarView;
//	public TextView titleView;
	public Menu paramMenu;
	
	public static HomeFragment homeFragment;
	public static CommentsTimeLineFragment commentFragment;
	public static MentionsTimeLineFragment mentionFragment;
	public static UserTimeLineFragment timelineFragment;
	public static FriendsFragment friendFragment;
	public static FollowersFragment followerFragment;
	
	public int currentItem;
	public List<String> homeGroupArray;
	public List<String> commentGroupArray;
	public int groupItem;
	
	@SuppressWarnings("deprecation")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.main_tabs);
        handler = new Handler(this);
        
        actionBar = getSupportActionBar();
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setDisplayShowTitleEnabled(false);
		byte[] iconByte = ServiceUtils.getImageFile("avatar.png", AppContext.USERHEADICON);
		Bitmap bitmap = ServiceUtils.bytesToBitmap(iconByte);
		if (bitmap != null) {
			actionBar.setLogo(new BitmapDrawable(bitmap));
		} else {
			actionBar.setLogo(R.drawable.logo);
		}
		
		homeGroupArray = new ArrayList<String>();
		homeGroupArray.add("全部微博");
		homeGroupArray.add("@我的微博");
		homeGroupArray.add("我的微博");
//		homeGroupArray.add("我的收藏");
//		homeGroupArray.add("未分组好友");
		
		commentGroupArray = new ArrayList<String>();
		commentGroupArray.add("所有评论");
		commentGroupArray.add("收到的评论");
		commentGroupArray.add("发出的评论");
		commentGroupArray.add("@我的评论");

        Context context = getSupportActionBar().getThemedContext();
        NavigationAdapter list = new NavigationAdapter(context, R.layout.sherlock_spinner_item, homeGroupArray);
        list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);

        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        actionBar.setListNavigationCallbacks(list, this);
		
		Bundle bundle = new Bundle();
		bundle.putString("userid", AppContext.getInstance().getUid());
		mAdapter = new TabsAdapter(getSupportFragmentManager(), this);
		mAdapter.addFragment("首页", HomeFragment.class, null);
		mAdapter.addFragment("评论", CommentsTimeLineFragment.class, null);
//		mAdapter.addFragment("@我", MentionsTimeLineFragment.class, null);
//		mAdapter.addFragment("微博", UserTimeLineFragment.class, bundle);
		mAdapter.addFragment("关注", FriendsFragment.class, bundle);
		mAdapter.addFragment("粉丝", FollowersFragment.class, bundle);
		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setOffscreenPageLimit(0);
		mPager.setAdapter(mAdapter);
		
		mIndicator = (TabPageIndicator) findViewById(R.id.indicator);
		mIndicator.setViewPager(mPager);
		mIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				currentItem = position;
				setNavigationMode();
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				
			}
		});
		getUserInfo();
    }
	
	public void setNavigationMode() {
		currentItem = mPager.getCurrentItem();
		Context context = getSupportActionBar().getThemedContext();
		if (currentItem == 0) {
	        NavigationAdapter list = new NavigationAdapter(context, R.layout.sherlock_spinner_item, homeGroupArray);
	        list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);

	        actionBar.setListNavigationCallbacks(list, this);
			actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		} else if (currentItem == 1) {
			NavigationAdapter list = new NavigationAdapter(context, R.layout.sherlock_spinner_item, commentGroupArray);
	        list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);

	        actionBar.setListNavigationCallbacks(list, this);
			actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		} else {
			actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		}
	}
    
	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		groupItem = itemPosition;
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>" + groupItem);
		currentItem = mPager.getCurrentItem();
		if (currentItem == 0) {
			if (homeFragment != null) {
				homeFragment.getTimelineFragment();
			}
		} else if (currentItem == 1) {
			if (commentFragment != null) {
				commentFragment.getCommentFragment();
			}
		}
		return false;
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	paramMenu = menu;
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case menu_new:
			Intent intent = new Intent(this, NewsActivity.class);
			intent.putExtra(AppContext.NEWTYPE, 1);
			startActivity(intent);
			break;
		case menu_refresh:
			currentItem = mPager.getCurrentItem();
			switch (currentItem) {
			case 0:
				if (homeFragment != null) {
					homeFragment.refreshTimelineFragment();
				}
				break;
			case 1:
				if (commentFragment != null) {
					commentFragment.menuRefresh();
				}
				break;
			case 2:
				if (mentionFragment != null) {
					mentionFragment.menuRefresh();
				}
				break;
			case 3:
				if (timelineFragment != null) {
					timelineFragment.menuRefresh();
				}
				break;
			case 4:
				if (friendFragment != null) {
					friendFragment.menuRefresh();
				}
				break;
			case 5:
				if (followerFragment != null) {
					followerFragment.menuRefresh();
				}
				break;
			default:
				break;
			}
			break;
		default:
			break;
		}
    	return false;
    }
    
    @Override
    public void showMenu() {
    	if (paramMenu != null) {
    		paramMenu.clear();
    		paramMenu.add(0, menu_new, 0, "发布").setIcon(R.drawable.ic_compose).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    		paramMenu.add(0, menu_refresh, 0, "刷新").setIcon(R.drawable.ic_refresh).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
  	    }
    }
    
    public void showOrHideProgress(boolean showOrHide) {
    	setSupportProgressBarIndeterminateVisibility(showOrHide);
    }
    
    public void setFragmentTitle() {
    }
    
    private void getUserInfo() {
    	new Thread() {
			public void run() {
				WeiboManager weibo = new WeiboManager(getApplicationContext());
				UserEntry entry = weibo.getUserByUserid(AppContext.getInstance().getUid());
				if (entry != null) {
					ServiceUtils.downLoadImage(entry.getProfile_image_url(), AppContext.USERHEADICON, "avatar.png");
					SharedPreferences sp = getSharedPreferences("user_info", Activity.MODE_APPEND);
					Editor editor = sp.edit();
					editor.putString("name", entry.getScreen_name());
					editor.commit();
					handler.sendEmptyMessage(get_userinfo);
				}
			};
		}.start();
    }

	@SuppressWarnings("deprecation")
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case get_userinfo:
	        byte[] iconByte = ServiceUtils.getImageFile("avatar.png", AppContext.USERHEADICON);
			Bitmap bitmap = ServiceUtils.bytesToBitmap(iconByte);
			if (bitmap != null) {
				actionBar.setLogo(new BitmapDrawable(bitmap));
			} else {
				actionBar.setLogo(R.drawable.logo);
			}
			break;
		case LOADFINISH:
			showOrHideProgress(false);
			showMenu();
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showExitTips();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			moveTaskToBack(true);
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	public void showExitTips() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.logout_home));
		builder.setPositiveButton(getString(R.string.confirm_ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						android.os.Process.killProcess(android.os.Process.myPid());
						System.exit(0);
						dialog.dismiss();
					}
				});
		builder.setNegativeButton(getString(R.string.confirm_cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.show();
	}
	
	public static class TabsAdapter extends FragmentPagerAdapter implements TitleProvider  {

    	private Context mContext;
		private final ArrayList<FragmentInfo> fragments = new ArrayList<FragmentInfo>();
		
		protected static final class FragmentInfo {
			private final String tag;
            private final Class<?> clss;
            private final Bundle args;

            protected  FragmentInfo(String _tag, Class<?> _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }
    	
		public TabsAdapter(FragmentManager fm, Context context) {
			super(fm);
			this.mContext = context;
		}
		
		public void addFragment(String tag, Class<?> clss, Bundle args) {
			FragmentInfo fragmentInfo = new FragmentInfo(tag, clss, args);
			fragments.add(fragmentInfo);
		}

		@Override
		public Fragment getItem(int arg0) {
			FragmentInfo fragmentInfo = fragments.get(arg0);
			Fragment fragment = Fragment.instantiate(mContext, fragmentInfo.clss.getName(), fragmentInfo.args);
			if (fragment.getClass().equals(HomeFragment.class)) {
				homeFragment = (HomeFragment) fragment;
			} else if (fragment.getClass().equals(CommentsTimeLineFragment.class)) {
				commentFragment = (CommentsTimeLineFragment) fragment;
			} else if (fragment.getClass().equals(MentionsTimeLineFragment.class)) {
				mentionFragment = (MentionsTimeLineFragment) fragment;
			} else if (fragment.getClass().equals(UserTimeLineFragment.class)) {
				timelineFragment = (UserTimeLineFragment) fragment;
			} else if (fragment.getClass().equals(FriendsFragment.class)) {
				friendFragment = (FriendsFragment) fragment;
			} else if (fragment.getClass().equals(FollowersFragment.class)) {
				followerFragment = (FollowersFragment) fragment;
			}
			return fragment;
		}

		@Override
		public int getCount() {
			return fragments.size();
		}

		@Override
		public String getTitle(int position) {
			return fragments.get(position).tag;
		}

    }
	
	public void loading() {
		try {
			if (this.isFinishing()) {
				return;
			}
			if (paramMenu != null) {
				paramMenu.clear();
			}
			showOrHideProgress(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void loadFinish() {
		handler.sendEmptyMessage(LOADFINISH);
	}
	
	public class NavigationAdapter extends ArrayAdapter<String> {

		private List<String> objects;
		private int textViewResourceId;
		private Context context;

		public NavigationAdapter(Context context, int textViewResourceId, List<String> objects) {
			super(context, textViewResourceId, objects);
			this.objects = objects;
			this.textViewResourceId = textViewResourceId;
			this.context = context;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView view = (TextView) LayoutInflater.from(context).inflate(textViewResourceId, null);
			view.setTextSize(18);
			view.setTextColor(Color.WHITE);
			view.setText(objects.get(position));
			return view;
		}

		@Override
		public View getDropDownView(int position, View convertView, ViewGroup parent) {
			TextView view = (TextView) LayoutInflater.from(context).inflate(textViewResourceId, null);
			view.setTextSize(18);
			view.setPadding(10, 10, 0, 10);
			view.setTextColor(Color.WHITE);
			view.setText(objects.get(position));
			return view;
		}
	}

}
